package com.apabi.service.impl;

import com.apabi.common.pojo.JqGridResult;
import com.apabi.mapper.SysIpMapper;
import com.apabi.mapper.SysTokenMapper;
import com.apabi.pojo.SysIp;
import com.apabi.pojo.SysToken;
import com.apabi.service.SysIpService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangxh.apabi on 2017/9/22.
 */
@Service
public class SysIpServiceImpl implements SysIpService{


    @Autowired
    private SysIpMapper sysIpMapper;

    @Autowired
    private SysTokenMapper sysTokenMapper;

    @Autowired
    private Sid sid;

    @Override
    public void saveSysIp(SysIp sysIp) {
        String itemId = sid.nextShort();
        sysIp.setId(itemId);
        sysIpMapper.insert(sysIp);
    }

    @Override
    public JqGridResult querySysIpList(String name, Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<SysIp> list =  sysIpMapper.selectAll();
        // 把ip表中的Tid,替换为Token,以方便展示查看
        for (SysIp ip: list) {
            SysToken sysToken = sysTokenMapper.selectByPrimaryKey(ip.getTid());
            ip.setTid(sysToken.getToken());
        }
        PageInfo<SysIp> pageList = new PageInfo<SysIp>(list);

        JqGridResult grid = new JqGridResult();
        grid.setTotal(pageList.getPages());
        grid.setRows(list);
        grid.setPage(pageList.getPageNum());
        grid.setRecords(pageList.getTotal());
        return grid;
    }

    @Override
    public SysIp querySysIpById(String sysIpId) {
        return sysIpMapper.selectByPrimaryKey(sysIpId);
    }

    @Override
    public void deleteSysIpById(String sysIpId) {
        sysIpMapper.deleteByPrimaryKey(sysIpId);
    }

    @Override
    public void updateSysIpById(SysIp sysIp) {
        sysIpMapper.updateByPrimaryKey(sysIp);
    }

    @Override
    public List<Map<String, String>> findLegalIpSegmentByToken(String token) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return sysIpMapper.findLegalIpSegmentByToken(token, dateString);
    }
}
